<?php
/**
 * Created by PhpStorm.
 * User: lenovo
 * Date: 2019/8/20
 * Time: 15:59
 */
namespace backend\service;

use common\component\Constant;
use common\models\base\AttachmentService;
class ImageService{

    const IMAGE_COMPRESS = 0;
    const IMAGE_CUT = 1;
    public static $thumbSizeCut = [
        Constant::ROUTE_CATEGORY_PRODUCT => [
            '200x200',#1:1
            '238x178',#4:3
        ],
        Constant::ROUTE_BRAND => [
           #待添加品牌图片
        ]
    ];

    public static $thumbSizeCompress = [
        Constant::ROUTE_CATEGORY_PRODUCT => [
        ],
        Constant::ROUTE_BRAND => [
            #待添加品牌图片
        ]
    ];


    /**
     * 根据图片生成剪切图
     * @param $image
     * @param $type
     */
    public function imageCut($image,$type=Constant::ROUTE_CATEGORY_PRODUCT) {
        $thumbs = self::$thumbSizeCut[$type];
        foreach ($thumbs as $size) {
            list($width,$height) = explode("x",$size);
            //生成缩略图
            $this->getImage($image,$width,$height);
        }
    }

    /**
     * 先生成压缩过渡图再进行剪切
     * @param $origin_image
     * @param $width
     * @param $height
     */
    public function getImage($origin_image,$width,$height) {
        #先压缩再剪切
        $image = \Yii::$app->params['attach.image.path'].$origin_image;
//        $imgInfo = getimagesize($image);
//        $img_w = $imgInfo[0]; #获取
//        $img_h = $imgInfo[1];
//        if ($img_w/$img_h>$width/$height) {
//            $img_w_new = $img_w;
//            $img_h_new = ceil(($img_w/$width)*$height);
//        } else {
//            $img_w_new = ceil(($width/$height)*$img_h);
//            $img_h_new = $img_h;
//        }
        $img_src = "_".$width."x".$height;;
        $image_transition = str_replace($this->getExt($image),'',$image).$img_src.$this->getExt($image);
        @unlink($image_transition);
        $this->getBlankImage($image,$width,$height);  #生成过渡图
//        return;
//        #生成过渡图后进行剪切
//        $img_src = "_".$img_w_new."x".$img_h_new;
//        $this->buildThumb($image_transition,$width,$height,self::IMAGE_COMPRESS,0,$img_src); #生成剪切图
//        #生成完成后删除过渡图
//        if (!in_array($img_src,['_200x200','_238x178'])) {
//            @unlink($image_transition);
//        }
    }

    /**
     * 根据图片生成压缩图
     * @param $image
     * @param $type
     */
    public function imageCompress($image,$type=Constant::ROUTE_CATEGORY_PRODUCT) {
        $path = \Yii::$app->params['attach.image.path'];
        $thumbs = self::$thumbSizeCompress[$type];
        if(!count($thumbs))return ;
        foreach ($thumbs as $origin => $size) {
            #获取origin_image
            $tmp = $image;
            $tmp = $path.str_replace($this->getExt($tmp),'',$tmp).$origin.$this->getExt($tmp);
            list($width,$height) = explode("x",$size);
            //生成缩略图
            @$this->buildThumb($tmp,$width,$height,self::IMAGE_COMPRESS,0,$origin);
        }
    }

    /**
     * 生成缩络图
     * @param $targetFile
     * @param $width
     * @param $height
     * @param $method
     * @param int $proportion
     * @param string $origin
     */
    private function buildThumb($targetFile,$width,$height,$method,$proportion = 0,$origin='') {
        @$image = \Yii::$app->image->load($targetFile);
        $imgInfo = getimagesize($targetFile);
        $img_w = $imgInfo[0];
        $img_h = $imgInfo[1];
        $dst_w = $name_w = $width;
        $dst_h = $name_h = $height;
        $x = $y = 0;

        if (($width > $img_w && $height > $img_h) || ($height > $img_h && $width == 0) || ($width > $img_w && $height == 0)){
            $proportion = 1;
        }
        if($width> $img_w)
        {

            $dst_w = $width = $img_w;
        }
        if($height> $img_h)
        {
            $dst_h = $height = $img_h;
        }
        if(!$width && !$height && !$proportion)
        {
            return false;
        }

        if (!$proportion) {
            //剪切
            if ($method == AttachmentService::IMAGE_CUT) {
                if (!$dst_h){
                    $height = $dst_h;
                }
                if (!$dst_w){
                    $width = $dst_w;
                }

                $judge = (($img_w > $dst_w) && ($img_h > $dst_h));

                $x = $judge ? ($img_w - $dst_w) / 2 : 0;
                $y = $judge ? ($img_h - $dst_h) / 2 : 0;

            } else {
                //压缩
                if ($dst_w xor $dst_h){
                    if ($dst_w && !$dst_h){
                        $propor = $dst_w / $img_w;
                        $height = $dst_h = $img_h * $propor;
                    }
                    elseif(!$dst_w && $dst_h){
                        $propor = $dst_h / $img_h;
                        $width = $dst_w = $img_w * $propor;
                    }
                }
            }
        } else {
            $proportion = min($proportion,1);
            $height = $dst_h = $img_h * $proportion;
            $width  = $dst_w = $img_w * $proportion;
        }

        if ($method == AttachmentService::IMAGE_CUT) {
            @$image->crop($width,$height,$x,$y)->background("#fff");
        } else {
            @$image->resize($width,$height,Image::NONE)->background("#fff");
        }
        $thumbImgPath = $this->getPath($targetFile);
        $thumbImgName = $this->getNameNew($targetFile,$origin) . "_".$name_w."x".$name_h;
        $thumbImgExt = $this->getExt($targetFile);
        $image->save($thumbImgPath.DIRECTORY_SEPARATOR.$thumbImgName.$thumbImgExt);
    }

    /**
     * 获取目录名
     * @param $fullPathAndFileName
     * @return bool|string
     */
    private function getPath($fullPathAndFileName) {
        return substr($fullPathAndFileName,0,strpos($fullPathAndFileName,strrchr($fullPathAndFileName,'/')));
    }

    /**
     * 获取文件名
     * @param $fullPathAndFileName
     * @param $origin
     * @return bool|string
     */
    private function getNameNew($fullPathAndFileName,$origin) {
        if ($origin) {
            $full_name = substr($fullPathAndFileName,strrpos($fullPathAndFileName,"/")+1);
            $name = substr($full_name,0,strrpos($full_name,$origin));
        } else {
            $full_name = substr($fullPathAndFileName,strrpos($fullPathAndFileName,"/")+1);
            $name = substr($full_name,0,strrpos($full_name,"."));
        }
        return $name;
    }

    /**
     * 获取文件后缀
     * @param $fullPathAndFileName
     * @return bool|string
     */
    private function getExt($fullPathAndFileName) {
        return substr($fullPathAndFileName,strrpos($fullPathAndFileName,"."));
    }

    /**
     * @param $src_path
     * @param $width
     * @param $height
     */
    private function getBlankImage($src_path,$width,$height) {
        $imgInfo = imagecreatefromstring(file_get_contents($src_path));
        $src_width = imagesx($imgInfo);
        $src_height = imagesy($imgInfo);

        //生成等比例的缩略图
        if ($src_width / $src_height >= $width / $height) {
            $tmp_image_width = $width;
            $tmp_image_height = round($tmp_image_width * $src_height / $src_width);
        } else {
            $tmp_image_height = $height;
            $tmp_image_width = round($tmp_image_height * $src_width / $src_height);
        }

        $tmpImage = imagecreatetruecolor($tmp_image_width, $tmp_image_height);
        imagecopyresampled($tmpImage, $imgInfo, 0, 0, 0, 0, $tmp_image_width, $tmp_image_height, $src_width, $src_height);

        //添加白边
        $final_image = imagecreatetruecolor($width, $height);
        $color = imagecolorallocate($final_image, 255, 255, 255);
        imagefill($final_image, 0, 0, $color);

        $x = round(($width - $tmp_image_width) / 2);
        $y = round(($height - $tmp_image_height) / 2);
        imagecopy($final_image, $tmpImage, $x, $y, 0, 0, $tmp_image_width, $tmp_image_height);
        $thumbImgPath = $this->getPath($src_path);
        $thumbImgName = $this->getNameNew($src_path,'') . "_".$width."x".$height;
        $thumbImgExt = $this->getExt($src_path);
        switch(strtolower($thumbImgExt))
        {
            case ".png":imagepng($final_image,$thumbImgPath.DIRECTORY_SEPARATOR.$thumbImgName.$thumbImgExt,9);break;
            case ".jpg":
            case ".jpeg":imagejpeg($final_image,$thumbImgPath.DIRECTORY_SEPARATOR.$thumbImgName.$thumbImgExt,100);break;
            case ".gif":imagegif($final_image,$thumbImgPath.DIRECTORY_SEPARATOR.$thumbImgName.$thumbImgExt,100);break;
        }
    }

}
